﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Segmentator.Dividers
{
    class DichotomyThreshold:ThresholdVariator
    {
        public static readonly string Name = "Дихотомическая процедура поиска порога";
        private double BestThreshold;
        /// <summary>
        /// Расхождение при прошлом значении порога. Его минимизируем...
        /// </summary>
        private double LastDistortion = Double.MaxValue;
        
        /// <summary>
        ///Инициализация границ 
        /// </summary>
        /// <param name="leftBound"></param>
        /// <param name="rightBound"></param>
        public DichotomyThreshold(double leftBound, double rightBound) : base(leftBound, rightBound)
        {
            Threshold = (RightBound + LeftBound) / 2;
            BestThreshold = (RightBound - LeftBound) / 2;

        }

        public override double next(double dist)
        {
            AnalizeDistortion(dist);
            return Threshold;
        }

        /// <summary>
        /// Анализирует и принимает решение о сдвиге левого или 
        /// правого порога
        /// </summary>
        /// <param name="dist"> Текущее расхождение</param>
        private void AnalizeDistortion(double dist)
        {
            if (LastDistortion > dist)
            {
                BestThreshold = Threshold;
                LastDistortion = dist;
            }
            Threshold = (RightBound + LeftBound) / 2.0;

            if (dist < 0)
            {
                LeftBound = Threshold;
            }
            else
            {
                RightBound = Threshold;
            }
                       
        }
    }
}
